<template>
  <div class="service-report-container" ref="chartContainer">
    <div v-show="chartData.length" class="chart-container">
      <div id="usage-amount-chart"></div>
      <div class="stats-table-expand no-border load-more-data-btn" :class="{'stats-table-isExpand': 0}">
        <button type="button" @click="loadMoreChartData" :disabled="disableLoadDataBtn" class="load-more-data-btn" :class="{'disabled-load-more-data-btn': disableLoadDataBtn}" >
          <!-- <i class="iconfont icon-zhankaisanjiao"></i>  -->
          {{btnText}}
        </button>
      </div> 
    </div>
    <stats-chart-empty v-show="!chartData.length && !loading">{{$t('common.base.tip.noData')}}</stats-chart-empty>

    <div class="table-container" v-show="specificData.length" ref="table">
      <div class="stats-task-table-header">
        <h3>{{$t('report.serviceUsageCrowdReport.title6')}}</h3>
        <div class="btn-group">
          <button type="button" class="btn btn-primary btn-sm" @click="exportData('export')" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="exportData('exportAll')" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="specificData = []">{{ $t('common.base.collapse') }}</button>
        </div>
      </div>

      <el-table stripe :data="specificData" class="stats-table">
        <el-table-column
          v-for="column in columns"
          :key="column.field"
          :label="column.label"
          :width="column.width"
          :prop="column.field"
          :show-overflow-tooltip="column.field !== 'taskNo'">

          <template slot-scope="scope">
            <template v-if="column.field === 'taskNo'">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip :content="scope.row.taskNo" placement="top" :disabled="!isContentTooltip">
                    <a href="#" @click="openDetail(scope.row)">{{scope.row.taskNo}}</a>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
            <template v-else-if="column.field === 'createTime'">{{scope.row.createTime | fmt}}</template>
            <template v-else-if="column.field === 'sale'">
              {{scope.row.sale.toFixed(2)}}
            </template>

            <template v-else-if="column.field === 'executorName'">
              <template v-if="isOpenData && scope.row.executorStaffId">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executorName }}
              </template>
            </template>

            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="stats-pagination"
        background @current-change="jump"
        :page-size="specificDataParams.pageSize"
        :current-page="specificDataParams.pageNum"
        layout="total, prev, pager, next"
        :total="specificDataTotalCount">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import _ from 'lodash';
import qs from 'src/util/querystring';
import echarts from 'packages/Echarts';
import SampleTooltip from 'packages/SampleTooltip'
import { checkButtonDisplayed } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

let chart = null;

export default {
  name: 'service-usage-amount-report',
  data() {

    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      chartData: [],
      specificData: [],
      chartDataTotalCount: 0,
      specificDataTotalCount: 0,
      specificDataParams: {
        servicePriceName: null,
        pageSize: 10,
        pageNum: 1,
      },
      columns: this.buildTableColumn(),
      requestOption:{
        params: {
          pageSize: 10,
          pageNum: 1,
        },
        url: '/api/report/outside/stats/servicePrice/getNumberByName',
        exportDataUrl: '/api/report/outside/stats/servicePrice/exportListByServicePriceName?',
        specificDataUrl: '/api/report/outside/stats/servicePrice/getListByServicePriceName',
      },
      paramsBackup: null,
      btnText: t('report.common.moreData'),
      loading: false,
    }
  },
  props: {
    requestParams: {
      type: Object,
    },
    chartType: {
      type: String,
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
    chartParams() {
      const params = {
        ...this.requestParams
      };
      if (!params.tagId) {
        delete params.tagId;
      }
      if (!params.taskTypeList) {
        delete params.taskTypeList;
      }
      return params;
    },
    disableLoadDataBtn () {
      return this.chartData.length === this.chartDataTotalCount;
    }
  },
  methods: {
    openDetail(row){
      if (!window.frameElement) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `taskView_${ row.taskId}`,
      //   title: `工单${row.taskNo}`,
      //   close: true,
      //   url: `/task/view/${row.taskId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.taskId,
        titleKey: row.taskNo,
        fromId
      })
    },
    loadMoreChartData() {
      this.requestOption.params.pageNum = this.requestOption.params.pageNum + 1;
      this.$nextTick(this.loadChartData);
    },
    jump(currentPage){
      this.specificDataParams.pageNum = currentPage;
      this.loadSpecificData();
    },
    exportData(type) {
      const params = {
        servicePriceName: this.specificDataParams.servicePriceName,
        exportType: type,
        ...this.requestParams,
      };

      if(!params.tagId) {
        delete params.tagId;
      }
      if(!params.taskTypeList) {
        delete params.taskTypeList;
      }

      params.source = 0;

      window.location.href = this.requestOption.exportDataUrl + qs.stringify(params);

      this.$emit('export-track', type === 'exportAll')
    },
    // The meaning of the parameter of p:
    // The parent component changes search condition(eg: tagId, timeStart, timeEnd) and set pageNum to 1.
    loadChartData(p = {}) {
      let instance = this.$loading.show(this.$refs.chartContainer);
      this.loading = true;

      const params = {
        ...this.chartParams,
        ...this.requestOption.params,
      };
      if (p && p.pageNum) {
        params.pageNum = p.pageNum;
        this.requestOption.params.pageNum = p.pageNum;
      }

      return this.$http.post(this.requestOption.url, params)
        .then(result => {
          if (result && result.pageNum > 1) {
            this.chartData = [...this.chartData, ...result.list];
          } else {
            this.chartData = result.list;
          }
          this.chartDataTotalCount = result.total;
          if(this.chartData.length === this.chartDataTotalCount) {
            this.btnText = t('report.common.moreDataSuc'); 
          } else {
            this.btnText = t('report.common.moreData'); 
          }

          if (chart) {
            this.renderChart();
            this.specificData = [];
          } else {
            this.$nextTick(this.initChart);
          }
          instance.hide();
          this.loading = false;
          return result;
        })
    },
    async loadSpecificData() {
      let instance = this.$loading.show(this.$refs.chartContainer);
      const params = {
        ...this.requestOption.params,
        ...this.specificDataParams,
        ...this.requestParams,
      };

      if(!params.tagId) {
        delete params.tagId;
      }
      if(!params.taskTypeList) {
        delete params.taskTypeList;
      }

      const result = await this.$http.post(this.requestOption.specificDataUrl, params);
      this.specificData = result.list;
      this.specificDataParams.pageNum = result.pageNum;
      this.specificDataTotalCount = result.total;
      instance.hide();
    },
    initChart(){
      if(!this.chartData.length) return;
      const dom = document.getElementById('usage-amount-chart');
      if (!dom) return;
      chart = echarts.init(dom);

      window.addEventListener('resize', _.debounce(function(){
        chart.resize();
      }));

      // 防止添加多次事件
      if (!chart._$handlers.click || !chart._$handlers.click.length) {
        // chart.on('click', event => {
        //   let origin = event.data._origin;
        //   this.specificDataParams.servicePriceName = origin.servicePriceName;
        //   this.specificDataParams.pageNum = 1;
        //   this.loadSpecificData();
        // });

        chart.getZr().off("click");
        chart.getZr().on("click", event => {
          // 获取点击位置
          const pointInPixel = [event.offsetX, event.offsetY];
          // 判断是否在坐标系内
          if (chart.containPixel("grid", pointInPixel)) {
            // 获取点击位置的坐标系[x，y]
            const yIndex = chart.convertFromPixel({ seriesIndex: 0 }, [event.offsetX, event.offsetY])[1];
            let option = chart.getOption()
            let yData = option.series[0].data[yIndex] 
            let origin = yData._origin;
            this.specificDataParams.servicePriceName = origin.servicePriceName;
            this.specificDataParams.pageNum = 1;
            this.loadSpecificData();
          }
        })
      }

      this.renderChart();
    },

    renderChart(){
      let option = this.buildChartOption();
      chart.setOption(option);
    },
    // build chart option.
    buildChartOption(){
      const axisData = [];
      const seriesData = [];

      if (!Array.isArray(this.chartData)) {
        this.chartData = [];
      }

      this.chartData.forEach(d => {
        axisData.push({
          value: d.servicePriceName,
          _origin: d,
        });
        seriesData.push({
          value: d.number,
          _origin: d,
        });
      });
      axisData.reverse();
      seriesData.reverse();

      let start = 0;
      let end = axisData.length - 1;
      // start = axisData.length - 3;
      if(axisData.length > 10) start = end - 9;

      return {
        xAxis: {
          type: 'value',
           
        },
        yAxis: {
          type: 'category',
          data: axisData,
          axisLabel: {
            formatter(originText) {
              if (!originText) return '';
              if(originText.length <= 10) {
                return originText
              }
              return `${originText.slice(0, 8)}...`;
            }
          },
        },
        toolbox: {
          right: 115,
          top: 10,
          feature: {
            saveAsImage: {
              name: `${t('common.fields.serviceName.displayName')}-${t('report.serviceUsageCrowdReport.title7')}`,
            },
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        dataZoom: [{
          type: 'slider',
          show: true,
          yAxisIndex: [0],
          right: '20px',
          startValue: start,
          endValue: end,
          minValueSpan: 10,
          maxValueSpan: 30
        }],
        series: [{
          name: t('report.serviceUsageCrowdReport.title3'),
          color: ['#6da9e8'],
          barMaxWidth: '30px',
          type: 'bar',
          data: seriesData,
          itemStyle : { normal: {label : {show: true}}}
        }],
        label: {
          normal: {
            show: true,
            position: 'right',
          }
        }
      };
    },
    buildTableColumn() {
      return [{
        label: t('common.label.taskNo'),
        field: 'taskNo',
        show: true,
      }, {
        label: t('common.label.taskTemplate'),
        field: 'templateName',
        show: true,
        width: '120px'
      }, {
        label: t('common.customer.customerName'),
        field: 'customerName',
        show: true,
      }, {
        label: t('common.fields.serviceItem.displayName'),
        field: 'servicePriceName',
        show: true,
      }, {
        label: t('common.part.serviceProviderNo'),
        field: 'serialNumber',
        show: true,
      }, {
        label: t('common.label.principalName'),
        field: 'executorName',
        show: true,
        width: '100px',
      }, {
        label: t('report.serviceUsageCrowdReport.title4'),
        field: 'number',
        show: true,
        width: '100px',
      }, {
        label: t('report.serviceUsageCrowdReport.title8'),
        field: 'createTime',
        show: true,
        width: '180px',
      }, {
        label: `${t('report.serviceUsageCrowdReport.title5')}（${t('common.label.unit')}：${t('common.base.yuan')}）`,
        field: 'sale',
        show: true,
        width: '160px',
      }]
    }
  },
  mounted(){
    this.$nextTick(() => {
      this.loadChartData()
        .then(this.initChart);
    })
  },
  activated() {
    if(this.paramsBackup
        && (this.requestParams.taskTypeList !== this.paramsBackup.taskTypeList
        || this.requestParams.tagId !== this.paramsBackup.tagId
        || this.requestParams.timeStart !== this.paramsBackup.timeStart
        || this.requestParams.timeEnd !== this.paramsBackup.timeEnd)
    ) {
      return this.loadChartData();
    }

    if(!chart) {
      this.initChart();
    }

  },
  deactivated() {
    const { taskTypeList, tagId, timeStart, timeEnd, } = this.requestParams;
    this.paramsBackup = {
      taskTypeList,
      tagId,
      timeStart,
      timeEnd,
    } 
  },
  components: {
    [SampleTooltip.name]: SampleTooltip
  }
}

</script>

<style lang="scss">
  .service-report-container {
    position: relative;
    min-height: 565px!important;

    #usage-amount-chart {
      min-height: 520px;
    }

    .chart-container {
      padding-bottom: 15px;
    }

    .load-more-chart-data-btn {
      display: block;
      margin: 0 auto;
    }

    .table-container {

      .table-header {
        display: flex;
        justify-content: space-between;
        h3 {
          margin: 0;
          height: 40px;
          line-height: 40px;
          font-size: 16px;
        }

        .btn-group {
          width: 192px;
          display: flex;
          justify-content: space-around;
          align-items: center;
        }
      }
    }
  }
</style>
